package com.chezai.client.server.codec;

import android.util.Log;

import com.chezai.client.server.util.ChannelUtil;
import com.jx.driving.message.Message;
import com.jx.driving.protocol.terminal.codec.Codec;
import com.jx.driving.protocol.terminal.codec.TerminalBodyCodec;

import java.util.List;

import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageCodec;

/**
 * 消息体解析
 *
 * @author shenliuyang
 *         <p>
 *         2016年8月12日下午3:14:48
 */
public class NettyTerminalBodyCodec extends MessageToMessageCodec<Message, Object> {

    private Codec codec = new TerminalBodyCodec();

    @Override
    protected void encode(ChannelHandlerContext ctx, Object msg, List<Object> out) throws Exception {
        Object content = codec.encode(ChannelUtil.getChannel(ctx.channel()), msg);
        if (content == null) {
            return;
        }
        if (content instanceof List) {
            out.addAll((List<Object>) content);
        }
    }

    @Override
    protected void decode(ChannelHandlerContext ctx, Message msg, List<Object> out) throws Exception {
        Object body = codec.decode(ChannelUtil.getChannel(ctx.channel()), msg);
        if (body == null) {
            return;
        }
        out.add(body);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        Log.e("head codec", "head codec 发生错误", cause);
    }

}
